package com.xr.sunnyday.security;

import com.alibaba.dubbo.config.annotation.Reference;
import com.xr.sunnyday.pojo.Permission;
import com.xr.sunnyday.pojo.Role;
import com.xr.sunnyday.pojo.User;
import com.xr.sunnyday.service.UserService;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

@Component
public class SpringSecurityUserService implements UserDetailsService {

    @Reference
    private UserService userService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //根据用户名去查询用户的相关信息(角色、权限)
        User user = userService.findByUsername(username);
        if (null!=user){
            //根据用户名获取对应的密码
            String password = user.getPassword();
            //定义用户权限的集合
            List<GrantedAuthority> authorities = new ArrayList<>();
            GrantedAuthority authority = null;
            //从用户中取出该用户拥有的角色(用户/角色是多对多)
            Set<Role> roles = user.getRoles();
            if (null!=roles){
                //【授予角色】把用户拥有的角色挨个添加到SimpleGrantedAuthority
                for (Role role : roles) {
                    authority = new SimpleGrantedAuthority(role.getKeyword());
                    authorities.add(authority);
                    //获取当前角色拥有的权限集合
                    Set<Permission> permissions = role.getPermissions();
                    if (null!=permissions){
                        for (Permission permission : permissions) {
                            //【授予权限】把该角色拥有的权限添加到SimpleGrantedAuthority
                            authority = new SimpleGrantedAuthority(permission.getKeyword());
                            authorities.add(authority);
                        }
                    }
                }

            }
            return new org.springframework.security.core.userdetails.User(username,password,authorities);


        }


        //没有该用户，直接返回null，限制访问
        return null;
    }
}
